<template>
  <n-config-provider :theme="theme">
    <n-message-provider>
      <div class="relative">
        <button
          @click="toggleDark"
          class="fixed z-50 p-2 transition bg-gray-200 rounded-full shadow top-4 right-4 dark:bg-gray-700 hover:scale-110"
          aria-label="切换深浅色模式"
        >
          <span v-if="isDark">🌙</span>
          <span v-else>☀️</span>
        </button>
        <div class="min-h-scree">
          <nav class="bg-white shadow-sm dark:bg-gray-800 dark:shadow-gray-700/20">
            <div class="px-4 mx-auto max-w-7xl sm:px-6 lg:px-8">
              <div class="flex justify-between h-16">
                <div class="flex">
                  <router-link 
                    to="/" 
                    class="flex items-center px-2 py-2 font-medium text-gray-900 dark:text-white"
                  >
                    🛠️ Vivian Tools
                  </router-link>
                </div>
                <div class="flex items-center">
                  <router-link 
                    to="/favorites" 
                    class="flex items-center px-3 py-2 text-sm font-medium text-gray-700 rounded-md dark:text-gray-300 hover:text-gray-900 dark:hover:text-white"
                  >
                    <span class="mr-1">⭐️</span>
                    收藏
                  </router-link>
                </div>
              </div>
            </div>
          </nav>

          <main class="mx-auto ">
            <router-view />
          </main>
        </div>
      </div>
    </n-message-provider>
  </n-config-provider>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { darkTheme, NConfigProvider, NMessageProvider } from 'naive-ui'
import { RouterView } from 'vue-router'

const theme = ref()
const isDark = ref(false)

function setThemeBySystem() {
  isDark.value = window.matchMedia('(prefers-color-scheme: dark)').matches
  console.log('setThemeBySystem', window.matchMedia('(prefers-color-scheme: dark)'))
}

function applyDarkClass(val: boolean) {
  document.documentElement.classList.toggle('dark', val)
}

function toggleDark() {
  isDark.value = !isDark.value
  localStorage.setItem('theme', isDark.value ? 'dark' : 'light')
  applyDarkClass(isDark.value)
}

onMounted(() => {
  const saved = localStorage.getItem('theme')
  if (saved === 'dark') isDark.value = true
  else if (saved === 'light') isDark.value = false
  else setThemeBySystem()
  applyDarkClass(isDark.value)
  // 监听系统主题变化
  window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
    if (!localStorage.getItem('theme')) {
      isDark.value = e.matches
    }
  })
})

watch(isDark, val => {
  theme.value = val ? darkTheme : undefined
}, { immediate: true })
</script>